<?php

namespace app\admin\controller;

use app\helpers\Common;
use app\common\model\Admin;

use think\facade\Db;
use think\facade\Cache;
use think\Exception;
use think\facade\View;
use think\Request;
use app\BaseController;

class Auth extends BaseController
{
    protected $middleware = [
        'adminAuth' => [
            'except' => ['login', 'doLogin']
        ],
    ];

    /**
     * Login
     */
    public function login()
    {
        $session_admin = session('admin');
        if ($session_admin && !empty($session_admin['id'])) {
            return redirect(url('index/index'));
        }

        return View::fetch();
    }

    /**
     * Ajax Login
     */
    public function doLogin(Request $request)
    {
        try {
            if ($request->isPost()) {
                $param = $request->param();
                $username = trim($param['name']);
                $password = trim($param['password']);
                $remember = $param['remember'] ?? 0;

                if (!$username) {
                    throw new Exception('登录名不能为空！');
                }
                if (!$password) {
                    throw new Exception('密码不能为空！');
                }

                $where = [
                    'name' => $username,
                ];
                $adminInfo = Db::name('admins')->where($where)->field('*')->find();
                if (!$adminInfo) {
                    throw new Exception('您的用户名不存在！');
                }
                if (!password_verify($password, $adminInfo['password'])) {
                    throw new Exception('密码错误！');
                }
                $captcha_code = trim($param['captcha_code']);
                $captcha_key = $param['captcha_key'] ?? '';
                if ($captcha_code) {
                    $verifyObj = new \app\common\service\Verify();
                    if (!$verifyObj->check($captcha_code, $captcha_key)) {
                        throw new Exception('验证码错误！');
                    }
                }

                $adminInfo = Admin::formatItem($adminInfo);

                $code = 200;
                $msg = '登录成功';
                $url = (string)url('index/index');

                $id = $adminInfo['id'];
                $token = md5(time() . uniqid(). mt_rand(1000, 9999));
                // 记录登录时间及IP等信息
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip' => get_IP(),
                    'token' => $token,
                    'token_expire' => time() + 3600*24*7
                ];
                $record = Admin::where('id', $id)->update($data);
                if (!$record) {
                    throw new Exception('服务异常，请重新登录！');
                }
                //session('ADMIN', $adminInfo);
                //$adminInfo = json_decode(json_encode($adminInfo), true);
                session('admin', $adminInfo);
                // 记住密码
                if ($remember) {
                    cookie('admin', json_encode($adminInfo), 3600*24*7);
                }
                // 日志
                $logRes = Common::actionLog($request, $id, '管理员登录', 0, json_encode([$adminInfo]));
            } else {
                throw new Exception('请求方式不正确');
            }
        } catch (Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
            $url = (string)url('auth/login');
        }

        $data = array(
            'code' => $code,
            'msg' => $msg,
            'data' => [
                'url' => $url,
                'token' => $token ?? ''
            ]
        );

        return json($data, 200);
    }

    /**
     * Logout
     */
    public function logout(Request $request)
    {
        session('admin', null);
        cookie('admin', null);

        Cache::tag('admin')->clear();

        // 清除浏览器 LocalStorage
        echo "<script>localStorage.clear();</script>";

        return redirect(url('auth/login'));
    }
}
